package com.hp.bon.sgw.wh.channel.handler;

import java.io.IOException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hp.bon.sgw.Constants;
import com.hp.bon.sgw.Constants.MessageType;
import com.hp.bon.sgw.bean.XmlMessage;
import com.hp.bon.sgw.core.BuzProcessorManager;
import com.hp.bon.sgw.core.CallParam;
import com.hp.bon.sgw.core.channel.SoapChannel;
import com.hp.bon.sgw.core.channel.handler.IAsynCallHandler;
import com.hp.bon.sgw.domain.MessageDetail;
import com.hp.bon.sgw.threads.MessageDetailCacheManager;
import com.hp.bon.sgw.threads.TaskManager;
import com.hp.bon.sgw.util.RSAUtil;
import com.hp.bon.sgw.wh.Constants.AliParam;
import com.hp.bon.sgw.wh.bean.SetChargeTaobao;
import com.hp.bon.sgw.wh.service.WHConfigService;
import com.hp.ocs.diameter.message.Message;

public class TaobaoHandler implements IAsynCallHandler {

	private static final Logger logger = LoggerFactory.getLogger(TaobaoHandler.class);
	PrintStream printStream;
	SetChargeTaobao taobao;
	private WHConfigService whConfigService;

	public TaobaoHandler(PrintStream printStream, SetChargeTaobao taobao,
			WHConfigService whConfigService) {
		this.printStream = printStream;
		this.taobao = taobao;
		this.whConfigService = whConfigService;
	}

	@Override
	public void onCallResult(CallParam callParam) {

		XmlMessage ack = null;
		Object response = null;

		if (callParam.getResponse() != null) {
			response = callParam.getResponse();
		} else if (callParam.getRecvResponse() != null) {
			response = callParam.getRecvResponse();
		}

		if (response == null) {
			ack = SoapChannel.createERRAnwser(
					callParam.getSessionId(),
					callParam.getRetCode() == 3002 ? 11202 : callParam
							.getRetCode(), callParam.getResultMsg());
		} else {
			if (response instanceof Message) {// CCA -> XML
				ack = BuzProcessorManager.getInstance().convertMessageToAck(
						callParam);
			} else if (response instanceof XmlMessage) {
				ack = (XmlMessage) response;
			} else {
				logger.warn("unknown response type:"
						+ callParam.getResponse().getClass().getName());
			}
		}
		try {
			String respXML = TaobaoConvertResponseString(ack);
			byte[] resp = respXML.getBytes("GBK");
			ack.setLength(resp.length);
			ack.setMsgTime(System.currentTimeMillis());
			printStream.write(resp);
			printStream.close();

			callParam.setResponse(ack);

			if (callParam.getRetCode() == Constants.ResultCode.SUCCESS) {// 成功的消息，请求应答入库

				MessageDetail detail = new MessageDetail();
				detail.setBusinessCallId(callParam.getBussinessCallId());
				detail.setSessionId(callParam.getSessionId());
				detail.setServiceContextId(callParam.getServiceContextId());
				detail.setMessageType(MessageType.WSA);
				detail.setDetails(ack.getDATA());
				detail.setMsgTime(new Date(ack.getMsgTime()));
				detail.setOpType("send");
				detail.setHostId(callParam.getUserName());
				MessageDetailCacheManager.getInstance().add(detail);
			}

			TaskManager.taskProcess(callParam);
			if (logger.isInfoEnabled()) {
				logger.info("http response(taobao) " + respXML);
			}

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	// 淘宝SOAP
	protected String TaobaoConvertResponseString(XmlMessage ack) {
		String respXML = null;

		String sign_type = whConfigService.getValue(AliParam.sign_type, "MD5");
		String aliPrivatekey = whConfigService.getValue(AliParam.privateKey, "");

		String sign = null;
		if (Integer.valueOf(ack.getRC()).intValue() != 0) {
			StringBuilder builder = new StringBuilder();
			builder.append("error").append(ack.getRC() + ack.getDS())
					.append("is_success").append("F").append("sign_type")
					.append(sign_type).append(aliPrivatekey);

			try {
				sign = RSAUtil.getReadableMD5Data(
						builder.toString().getBytes("GBK")).toLowerCase();
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			respXML = "<?xml version=\"1.0\" encoding=\"GBK\"?><isp><is_success>F</is_success>";
			respXML = respXML + "<error>" + ack.getRC() + ": " + ack.getDS()
					+ "</error><sign>" + sign + "</sign><sign_type>"
					+ sign_type + "</sign_type></isp>";

		} else {

			String orinData = ack.getDATA();
//			logger.info("orinData-----" + orinData);
			if (orinData != null) {
				String is_success = "F";
				String error = null;
				Document doc = null;
				try {
					doc = DocumentHelper.parseText(orinData);
					Element root = doc.getRootElement();

					Node node = root
							.selectSingleNode("//Service_Information/is_success");
					if (node != null) {
						is_success = node.getStringValue();
					}
					node = root.selectSingleNode("//Service_Information/error");
					if (node != null) {
						error = node.getStringValue();
					}
					StringBuilder builder = new StringBuilder();
					builder.append("is_success").append(is_success)
							.append("error").append(error).append("sign_type")
							.append(sign_type).append(aliPrivatekey);

					try {
						sign = RSAUtil.getReadableMD5Data(
								builder.toString().getBytes("GBK"))
								.toLowerCase();
					} catch (UnsupportedEncodingException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					respXML = "<?xml version=\"1.0\" encoding=\"GBK\"?><isp><is_success>"
							+ is_success
							+ "</is_success><error>"
							+ error
							+ "</error><sign>"
							+ sign
							+ "</sign><sign_type>"
							+ sign_type + "</sign_type></isp>";

					if (is_success.equalsIgnoreCase("T")) {
						// String order_status =
						// root.selectSingleNode("//order_status").getStringValue();
						// String tb_order_id =
						// root.selectSingleNode("//tb_order_id").getStringValue();
						// String out_order_id =
						// root.selectSingleNode("//out_order_id").getStringValue();
						// String alipay_order_no =
						// root.selectSingleNode("//alipay_order_no").getStringValue();
						// String seller_alipay_id =
						// root.selectSingleNode("//seller_alipay_id").getStringValue();
						// String deduct_money =
						// root.selectSingleNode("//deduct_money").getStringValue();

						String order_status = taobao.getOrder_status();
						String tb_order_id = taobao.getTb_order_id();
						String out_order_id = taobao.getOut_order_id();
						String alipay_order_id = taobao.getAlipay_order_id();
						String seller_alipay_id = taobao.getSeller_alipay_id();
						String deduct_money = taobao.getDeduct_money();

						builder = new StringBuilder();
						builder.append("alipay_order_no")
								.append(alipay_order_id).append("deduct_money")
								.append(deduct_money).append("is_success")
								.append(is_success).append("order_status")
								.append(order_status).append("out_order_id")
								.append(out_order_id)
								.append("seller_alipay_id")
								.append(seller_alipay_id).append("sign_type")
								.append(sign_type).append("tb_order_id")
								.append(tb_order_id).append(aliPrivatekey);
//						logger.info("----------" + builder.toString());

						try {
							sign = RSAUtil.getReadableMD5Data(
									builder.toString().getBytes("GBK"))
									.toLowerCase();
						} catch (UnsupportedEncodingException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

						respXML = "<?xml version=\"1.0\" encoding=\"GBK\"?><isp><is_success>"
								+ is_success
								+ "</is_success><response><order_status>"
								+ order_status
								+ "</order_status><tb_order_id>"
								+ tb_order_id
								+ "</tb_order_id><out_order_id>"
								+ out_order_id
								+ "</out_order_id><alipay_order_no>"
								+ alipay_order_id
								+ "</alipay_order_no><seller_alipay_id>"
								+ seller_alipay_id
								+ "</seller_alipay_id><deduct_money>"
								+ deduct_money
								+ "</deduct_money></response><sign>"
								+ sign
								+ "</sign><sign_type>"
								+ sign_type
								+ "</sign_type></isp>";
					}
					// 异常返回
					// else {
					// String error = Myutils.convert(orinData, "error");
					// StringBuilder builder = new StringBuilder();
					// builder.append("is_success").append(is_success)
					// .append("error").append(error)
					// .append("sign_type").append(sign_type)
					// .append(PRIVATEKEY);
					// ;
					// try {
					// sign = RSAUtil.getReadableMD5Data(
					// builder.toString().getBytes("GBK"))
					// .toLowerCase();
					// } catch (UnsupportedEncodingException e) {
					// // TODO Auto-generated catch block
					// e.printStackTrace();
					// }
					// respXML =
					// "<?xml version=\"1.0\" encoding=\"GBK\"?><isp><is_success>"
					// + is_success
					// + "</is_success><error>"
					// + error
					// + "</error><sign>"
					// + sign
					// + "</sign><sign_type>"
					// + sign_type
					// + "</sign_type></isp>";
					// }
				} catch (DocumentException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		}
		return respXML;
	}

	@Override
	public int getProtocolType() {
		return 5;
	}
}
